<template>
  <div class="app-container">
    <div class="head">
      <img src="@/assets/img/Layout/position.png" />
      <p class="see-block">客户列表</p>
    </div>
    <div class="view-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="客户名称" prop="searchValue">
          <el-input
            v-model="queryParams.searchValue"
            placeholder="请输入客户名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" class="list-search btn-success" color="#5ED4D4">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" class="list-search">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            class="btn-success"
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="userAdd()"
            v-hasPermi="['system:customerInformation:insert']"
          >新建</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            class="btn-scanCodeDel"
            type="primary"
            icon="el-icon-download"
            size="mini"
            @click="btnExport()"
          >导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            class="btn-scanCodeDel"
            type="primary"
            icon="el-icon-download"
            size="mini"
            @click="btnTemplate()"
            v-hasPermi="['system:excelExport:template']"
          >模版下载</el-button>
        </el-col>
        <el-col :span="17">
          <el-upload
            v-hasPermi="['system:excelImport:importCustomer']"
            action="#"
            accept=".xlsx,.xls"
            :auto-upload="false"
            :on-change="btnImportCustomer"
          >
            <el-button class="btn-approve" icon="el-icon-upload2" size="mini" type="primary">客户导入</el-button>
          </el-upload>
        </el-col>
        <el-col :span="1">
          <el-popover placement="bottom" title="筛选列" trigger="click" width="40">
            <el-checkbox-group v-model="checkedColumns" size="mini">
              <el-checkbox v-for="item in checkBoxGroup" :key="item" :label="item" :value="item"></el-checkbox>
            </el-checkbox-group>
            <div title="筛选列" class="filter-table-col" slot="reference">
              <img src="@/assets/img/screening.png" width="25" />
            </div>
          </el-popover>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="userList" @row-click="handleView" :default-sort="{prop: 'date', order: 'descending'}" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="35" align="center" />
        <el-table-column label="序号" type="index" align="center" width="50">
           <template slot-scope="scope">
            <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <template v-for="(item, index) in tableHeaderData">
          <el-table-column
            :label="item.label"
            :prop="item.prop"
            :align="item.align"
            :sortable="item.sortable"
            :show-overflow-tooltip="true"
            :key="index"
            :width="item.width"
            v-if="colData[index].isTrue"
          >
            <template slot-scope="scope">
              <template v-if="item.label == '审核状态'">
                <div v-if="scope.row.approvalStatus == 0" style="color:#13C2C2">草稿</div>
                <div v-if="scope.row.approvalStatus == 1" style="color:#13C2C2">待审核</div>
                <div v-if="scope.row.approvalStatus == 2" style="color:#52C41A">已审核</div>
                <div v-if="scope.row.approvalStatus == 3" style="color:#fd562c">拒绝</div>
              </template>
              <template v-else-if="item.label == '状态'">
                <div v-if="scope.row.status == 0" style="color:#13C2C2">禁用</div>
                <div v-if="scope.row.status == 1" style="color:#52C41A">正常</div>
              </template>
              <span v-else>{{ scope.row[scope.column.property] }}</span>
            </template>
          </el-table-column>
        </template>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click.native.stop="handleDelete(scope.row)"
              v-hasPermi="['system:customerInformation:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script>
import { listUser, userDelete } from "@/api/system/basedata/user/user"
import { exportCustomer, exportTemplate, exportImportCustomer } from "@/api/system/export/export"
// import { listSalesArea } from "@/api/system/basedata/salesarea/salesarea"

export default {
  name: "plan",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 生产列表数据
      userList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        searchValue:undefined
      },
      ids: [],
      tableHeaderData: [
        { label: "编号", align: "center", prop: "code", width: "180", sortable: true },
        { label: "名称", align: "center", prop: 'name', width: "180" },
        // { label: "简称", align: "center", prop: "abbreviation" },
        // { label: "销售区域", align: "center", prop: "salesAreaName"},
        { label: "币种", align: "center", prop: "currency"},
        { label: "联系人", align: "center", prop: "contact" },
        // { label: "付款条件", align: "center", prop: "paymentTerms"},
        { label: "创建者", align: "center", prop: "createBy", width: "150"  },
        { label: "审核状态", align: "center", prop: "approvalStatus" },
        { label: "状态", align: "center", prop: "status" },
        { label: "最后更新", align: "center", prop: "updateBy", width: "150"  },
      ],
      colData: [
        { title: "编号", isTrue: true },
        { title: "名称", isTrue: true },
        // { title: "简称", isTrue: true },
        // { title: "销售区域", isTrue: true },
        { title: "币种", isTrue: true },
        { title: "联系人", isTrue: true },
        // { title: "付款条件", isTrue: true },
        { title: "创建者", isTrue: true },
        { title: "审核状态", isTrue: true },
        { title: "状态", isTrue: true },
        { title: "最后更新", isTrue: true },
      ],
      // 当前选中的多选框，代表当前展示的列
      // checkedColumns: ["编号", "名称", "简称", "销售区域", "币种", "联系人", "付款条件", "创建者", "审核状态", "状态", "最后更新"],
      checkedColumns: ["编号", "名称", "币种", "联系人", "创建者", "审核状态", "状态", "最后更新"],
      // 多选框的列表，列出表格的每一列
      // checkBoxGroup: ["编号", "名称", "简称", "销售区域", "币种", "联系人", "付款条件", "创建者", "审核状态", "状态", "最后更新"]
      checkBoxGroup: ["编号", "名称", "币种", "联系人", "创建者", "审核状态", "状态", "最后更新"]
    }
  },
  watch: {
    checkedColumns(val) {
      let arr = this.checkBoxGroup.filter(i => !val.includes(i));
      this.colData.filter(i => {
        if (arr.indexOf(i.title) != -1) {
          i.isTrue = false;
        } else {
          i.isTrue = true;
        }
      });
      this.reload = Math.random()
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表
    getList() {
      this.loading = true
      listUser(this.addDateRange(this.queryParams)).then(res => {
          this.userList = res.rows
          this.total = res.total
          this.loading = false
          // this.getSalesArea()
      })
    },
    // getSalesArea(){
    //   listSalesArea().then(res => {
    //       this.userList.forEach(item => {
    //       let arr = res.rows.find(e =>{
    //         return e.areaId == item.salesArea
    //       })
    //       if(arr != undefined){
    //         item.salesArea = arr.areaName
    //       }
    //     })
    //   })
    // },
    // 搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置按钮
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 新建
    userAdd(){
      this.$router.push({path:"/basedata/user/add"})
    },
    // 查看详情
    handleView(row) {
      this.$router.push({path:"/basedata/user/detail",query:{id: row.id}})
    },
    // 删除
    handleDelete(row){
      this.$modal.confirm('是否确认删除？').then(() => {
        userDelete(row.id).then(() => {
          this.getList()
          this.$modal.msgSuccess("删除成功")
        })
      }).catch(() => {})
    },
    // 多选框选中数据
    handleSelectionChange(row) {
      this.ids = row.map(item => item.id)
    },
    // 导出
    btnExport(){
      let a = this.colData.filter(i => {
        return i.isTrue == true
      })
      let b = []
      a.forEach((item) => {
        this.tableHeaderData.forEach((data) => {
          if(item.title == data.label){
            b.push({name: data.prop, value: item.title})
          }
        })
      })
      const obj = b.reduce((result, item) => {
        result[item.name] = item.value
        return result
      }, {})
      if(this.ids.length > 0){
        let data = {
          ids: this.ids,
          headMap: obj,
          searchValue: this.queryParams.searchValue,
        }
        this.getExport(data)
      }else{
        let data = {
          headMap: obj,
          searchValue: this.queryParams.searchValue
        }
        this.getExport(data)
      }
    },
    getExport(data){
      this.$modal.loading("正在导出")
      exportCustomer(data).then(res => {
        this.$modal.closeLoading()
        let blob = new Blob([res], {
          type: res.type,
        })
        let downloadElement = document.createElement("a")
        let href = window.URL.createObjectURL(blob)
        downloadElement.href = href
        downloadElement.download = "客户列表.xls"
        document.body.appendChild(downloadElement)
        downloadElement.click()
        window.URL.revokeObjectURL(href)
      })
    },
    // 模版下载
    btnTemplate(){
      this.$modal.loading("正在下载")
      exportTemplate(2).then(res => {
        this.$modal.closeLoading()
        let blob = new Blob([res], {
          type: res.type,
        })
        let downloadElement = document.createElement("a")
        let href = window.URL.createObjectURL(blob)
        downloadElement.href = href
        downloadElement.download = "客户模版.xlsx"
        document.body.appendChild(downloadElement)
        downloadElement.click()
        window.URL.revokeObjectURL(href)
      })
    },
    // 客户导入
    btnImportCustomer(item){
      this.$modal.loading("正在导入")
      let formData = new FormData()
      let file = item.raw
      formData.append('file', file)
      exportImportCustomer(formData).then(res => {
        if(res.code == 200){
          this.$modal.closeLoading()
          this.$modal.msgSuccess("导入成功")
          this.getList()
        }else{
          this.$modal.closeLoading()
          this.$modal.msgError(res.msg)
        }
      })
    }
  }
}
</script>

<style scoped>
::v-deep .el-upload-list{
  display: none;
}
</style>